//
//  MCHaveVideoTrainVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/21.
//

import UIKit
import AVFoundation
import MetalKit
import QMUIKit
import SwiftAudioPlayer
import SJVideoPlayer
import Toast_Swift

class MCHaveVideoTrainVc: MCBaseVc {

    
    public var planId:String = ""
    
    public var userPlanId:String = ""
    
    @IBOutlet weak var previewPlayView: MTKView!
    @IBOutlet weak var videoPlayerView: UIView!
    @IBOutlet weak var stopBtn: UIButton!
    @IBOutlet weak var selectBtn: UIButton!
    @IBOutlet weak var startBtn: UIButton!
    
    
    
    fileprivate var mScreenRecController:ScreenRecController!
    
    var playerVideo:SJVideoPlayer!
    
    //自定义录制视频预览
    var device:MTLDevice!
    var commandQueue:MTLCommandQueue!
    var captureSession:AVCaptureSession!
    var backCameraInput:AVCaptureDeviceInput!
    var frontCameraInput:AVCaptureDeviceInput!
    var videoPreviewLayer:AVCaptureVideoPreviewLayer!
    
    fileprivate var isRec:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        
        mScreenRecController = ScreenRecController()
        mScreenRecController.setEventListener(self)
        
        let notificationCenter = NotificationCenter.default
        
        notificationCenter.addObserver(self, selector: #selector(self.viewDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
        
        
        playerVideo = SJVideoPlayer.lightweight()
        playerVideo.view.frame = self.videoPlayerView.bounds
        playerVideo.defaultEdgeControlLayer.isHiddenBackButtonWhenOrientationIsPortrait = true
        self.videoPlayerView.addSubview(playerVideo.view)
        
        let asset = SJVideoPlayerURLAsset(url: URL(string: "http://aliuwmp3.changba.com/userdata/video/45F6BD5E445E4C029C33DC5901307461.mp4")!)
        playerVideo.urlAsset = asset
        
        previewPlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        previewPlayView.contentMode = .scaleAspectFit
        
        device = MTLCreateSystemDefaultDevice()
        previewPlayView.device = device
        
        commandQueue = previewPlayView.device?.makeCommandQueue()
        
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .photo
        
        
        setupLivePreview()
        
        guard let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else { return }
        guard let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else { return }
        
        do {
            backCameraInput = try AVCaptureDeviceInput(device: backCamera)
            frontCameraInput = try AVCaptureDeviceInput(device: frontCamera)
            
            let photoOutPut = AVCapturePhotoOutput()
            photoOutPut.isHighResolutionCaptureEnabled = true
            
            if captureSession.canAddInput(backCameraInput), captureSession.canAddOutput(photoOutPut) {
                captureSession.addInput(backCameraInput)
                captureSession.addOutput(photoOutPut)
            }
            
        } catch {
            print(error.localizedDescription)
        }
        
        startCaptureSession()
        
        SAPlayer.shared.startRemoteAudio(withRemoteUrl: URL(string: "https://peic-sport-1253971651.cos.ap-nanjing.myqcloud.com/2023/05/28/1662712784416595968.mp3")!)
        SAPlayer.shared.play()
        
        
    }
    
    
    private func render() -> Void {
        guard let renderPassDescriptor = previewPlayView.currentRenderPassDescriptor else { return }
        guard let commandBuffer = commandQueue.makeCommandBuffer() else { return }
        guard let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { return }
        guard let currentDrawable = previewPlayView.currentDrawable else { return }
        commandEncoder.endEncoding()
        commandBuffer.present(currentDrawable)
        commandBuffer.commit()
    }
    
    
        
    func setupLivePreview() -> Void {
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer.videoGravity = .resizeAspectFill
        videoPreviewLayer.connection?.videoOrientation = .portrait
        previewPlayView.layer.insertSublayer(videoPreviewLayer, at: 0)
        DispatchQueue.main.async {
            self.videoPreviewLayer.frame = self.previewPlayView.bounds
        }
        
        
    }
    
    func startCaptureSession() -> Void {
        DispatchQueue.global(qos: .userInitiated).async {
            self.captureSession.startRunning()
        }
    }
    
    override var shouldAutorotate: Bool {
        return false
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playerVideo.vc_viewDidAppear()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        playerVideo.vc_viewDidDisappear()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        playerVideo.vc_viewDidDisappear()
    }
    
    
   @objc func viewDidEnterBackground(_ notification:Notification?) -> Void {
       
        if isRec {
            mScreenRecController.stop()
        }else{
            mScreenRecController.stopWithBackground()
        }
    }
    
    @IBAction func startSender(_ sender: UIButton) {
        if isRec  {
            mScreenRecController.pause()
        }else {
            mScreenRecController.getScreenRecordingPermission { success in
                if success {
                    self.mScreenRecController.start()
                }
            }
        }
    }
    
    @IBAction func stopSender(_ sender: UIButton) {
      
        self.mScreenRecController.pause()
    }
    
}

extension MCHaveVideoTrainVc:MTKViewDelegate {
    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        
    }
    func draw(in view: MTKView) {
        render()
    }
}


extension MCHaveVideoTrainVc:ScreenRecControllerDelegate {
    func onRecPause() {
        DispatchQueue.main.async {
            self.mScreenRecController.stop()
             
        }
    }
    
    func onRecStart() {
        DispatchQueue.main.async {
            self.isRec = true
            
        }
    }
    
    func onRecComplete() {
        DispatchQueue.main.async {
            self.mScreenRecController._release()
            self.view.makeToast("保存成功",position: .center)
            self.mScreenRecController.resume()
            
        }
    }
    
    func onRecFail(with error: ScreenRecError) {
        
    }
    
    func onUpdateRecTime(with sec: Int) {
        print(sec)
    }
    
}
